goog.provide('PhotoManager');
goog.provide('Photo');

goog.require('goog.net.XhrIo');

/**
 * @constructor
 */
Photo = function(photoId, imageUrl) {
    this.photoId = photoId;
    this.imageUrl = imageUrl;
};


/**
 * @constructor
 */
PhotoManager = function(userId, albumId, pageSize) {
    this.albumId = albumId;
    this.userId = userId;
    this.pageSize = pageSize;
    this.currentPhotos = null;
    this.pageStart = 1;  // 1, not 0. Duh.
    this.morePages = false;
    this.scriptElement = goog.dom.createElement('script');
    this.scriptLoading = false;
};

PhotoManager.prototype.constructFeedUrl = function() {
    return "/data/feed/api/user/" +
	this.userId + "/albumid/" + this.albumId +
	"?alt=json&start-index=" + this.pageStart +
	"&max-results=" + this.pageSize;
};

PhotoManager.prototype.load = function(loadCallback) {
    if (!this.albumId || !this.userId) {
	loadCallback(false);
    }
    goog.net.XhrIo.send(this.constructFeedUrl(), goog.bind(function(e) {
	window.console.log(e.target.getResponseJson());
	var xhr = e.target;
	if (!xhr.isSuccess()) {
	    window.console.log('Error sending request.');
	    window.console.log(xhr.getLastErrorCode());
	    loadCallback(false);
	    return;
	}
	var obj = xhr.getResponseJson();
	if (!this.buildPhotoList(obj)) {
	    window.console.log('Response had incomplete data.');
	    loadCallback(false);
	    return;
	}
	loadCallback(true);
    }, this));
};

PhotoManager.prototype.buildPhotoList = function(responseObj) {
    this.currentPhotos = Array();
    var feed = responseObj['feed'];
    if (!feed) {
	return false;
    }

    goog.array.forEach(feed['entry'],
		       goog.bind(function(e) {
			   var p = new Photo(e['gphoto$id']['$t'],
					     e['content']['src']);
			   this.currentPhotos.push(p);
		       }, this));
    var numCurrResults = this.currentPhotos.length;
    this.pageStart = feed['openSearch$startIndex']['$t'];
    this.morePages = (this.pageStart - 1 + numCurrResults)
	> feed['openSearch$totalResults']['$t'];
    return true;
};

PhotoManager.prototype.getPhotos = function() {
    return this.currentPhotos;
};
